<!--站点列表页-->
<template>
    <div class="wrap">
        <m-page-list
                :page="page"
                :total="page.total"
                :option="option"
                :table-data="tableData"
                :table-loading="tableLoading"
        >
            <template #hLSlot v-if="shuttleData.shuttle_seat_id && shuttleData.shuttle_seat_id !== shuttleData.shuttle_id">
                <div style="height: 100%;display: flex;align-items: center;">关联座位表：{{shuttleData.shuttle_seat_name}} 座位表</div>
            </template>
        </m-page-list>
        <m-dialog-form ref="dialogRef" :data="dialogData" v-model:show="dialogShow" :option="dialogOption" @confirm="dialogConfirm" ></m-dialog-form>

        <m-dialog-form ref="mDialogRef" :data="mDialog.data" v-model:show="mDialogShow" :option="mDialog" @confirm="handleConfirm" ></m-dialog-form>

        <el-dialog class="dialog-wrap" v-model="showQrcode" title="留位链接" :close-on-click-modal="false">
            <div v-show="!isBuilded">
                <m-form ref="formRef" :fields="linkField" :value="linkParam" :changeFn="handleChange"></m-form>

            </div>
            <div v-if="isBuilded" class="qrcode-wrap" style="">
                <div class="title">截图区域</div>
                <div class="content">
                    <qrcode-vue errorLevel="L" :value="qrcodeLink" size="400" render-as="svg"></qrcode-vue>
                    <div style="margin-top: 10px;font-size: 16px;">{{shuttleData.shuttle_name}}</div>
                </div>
            </div>
            <template #footer>
                <el-button v-show="!isBuilded" type="primary" @click="buildConfirm">生成链接</el-button>

                <el-button v-show="isBuilded" @click="isBuilded = false">返回</el-button>
                <el-button v-show="isBuilded" type="primary" @click="copyQrcode">复制链接</el-button>
                <el-button v-show="isBuilded" type="primary" @click="buildImage">下载二维码</el-button>
            </template>
        </el-dialog>
    </div>

</template>

<script setup>
  import {ref,reactive,onMounted,inject,defineProps,defineEmits,watch,onBeforeMount} from 'vue'
  import QrcodeVue from 'qrcode.vue'
  import MForm from '@/components/common/Form/Form'
  import { copyText, str2Base64} from "../../utils/utils";
  //组件
  import MPageList from '@/components/PageList'
  import MDialogForm from '@/components/DialogForm/DialogForm'
  //请求
  import {getShuttleSeat, addShuttleSeat,editShuttleSeat,editShuttleSeatList,delShuttleSeat,delShuttleSeatBySid,
    clearMonthTicket,getSeatStatus,getTicketType,getStop,getIdentificationType,publicAllData,editShuttle,getPackageTypeBySchool,
    changeShuttleSeatName} from '@/request/api/basicData'

  import {usePageList} from "./relPage";
  //引用类型字段参数
  import {refOpt} from "../const";
  import {uuid} from "../../utils/uuid";
  import {getAuthority} from "../../utils/permission";

  const props = defineProps(['shuttleData']),
    emit = defineEmits(['update:shuttleData']);
  const refresh = inject('refresh')

  let opts = {
    auth_id: 'shuttleSeat',
    getApi: getShuttleSeat,addApi:addShuttleSeat,editApi:editShuttleSeat,delApi:delShuttleSeat,
    idKey: 'stop_id',
    cols: [
      {prop: 'seat_no',label: '座位号',fixed: 'left' },

      {prop: 'seat_status_name',label: '座位状态',fixed: 'left',width: 100,templte:(scope) =>{
          let {seat_status_name, seat_status_name_leave} = scope.row;
          return `上：${seat_status_name || ''}</br>放：${seat_status_name_leave || ''}`
        } } ,
      // {prop: 'seat_status_name_leave',label: '回程座位状态名称' },

      {prop: 'ticket_typall_name',label: '票种名称',width: 130,templte:(scope) =>{
          let {ticket_typall_name, ticket_typall_name_leave} = scope.row;
          return `上：${ticket_typall_name || ''}</br>放：${ticket_typall_name_leave || ''}`
        }  },
      // {prop: 'up_stop_id',label: '去程站点编号'  },
      {prop: 'up_stop_name',label: '站点名称',width: 220,templte:(scope) =>{
          let {up_stop_name, down_stop_name} = scope.row;
          return `上：${up_stop_name || ''}</br>放：${down_stop_name || ''}`
        }  },
      {prop: 'identification_no',label: '证件号码',width: 230,templte:(scope) =>{
          let {identification_no, identification_no_leave} = scope.row;
          return `上：${identification_no || ''}</br>放：${identification_no_leave || ''}`
        }},
      // {prop: 'identification_type_id',label: '证件类型编号'},
      {prop: 'identification_type_name',label: '证件类型名称',width: 120,templte:(scope) =>{
          let {identification_type_name, identification_type_name_leave} = scope.row;
          return `上：${identification_type_name || ''}</br>放：${identification_type_name_leave || ''}`
        } },
      // {prop: 'passengers_id',label: '乘车人编号'},
      {prop: 'passengers_name',label: '乘车人名称',width: 120,templte:(scope) =>{
          let {passengers_name, passengers_name_leave} = scope.row;
          return `上：${passengers_name || ''}</br>放：${passengers_name_leave || ''}`
        }},
      // {prop: 'customer_id',label: '客户编号'},
      {prop: 'customer_name',label: '客户名称',width: 120,templte:(scope) =>{
          let {customer_name, customer_name_leave} = scope.row;
          return `上：${customer_name || ''}</br>放：${customer_name_leave || ''}`
        }},
      {prop: 'out_trade_no',label: '订单号',width: 270 ,templte:(scope) =>{
          let {out_trade_no, out_trade_no_leave} = scope.row;
          return `上：${out_trade_no || ''}</br>放：${out_trade_no_leave || ''}`
        }},
      {prop: 'effective_time_start',label: '车票有效时间起',width: 220 ,templte:(scope) =>{
          let {effective_time_start, effective_time_start_leave} = scope.row;
          return `上：${effective_time_start || ''}</br>放：${effective_time_start_leave || ''}`
        } },
      {prop: 'effective_time_end',label: '车票有效时间止',width: 220 ,templte:(scope) =>{
          let {effective_time_end, effective_time_end_leave} = scope.row;
          return `上：${effective_time_end || ''}</br>放：${effective_time_end_leave || ''}`
        } },
      {prop: 'privileged_code',label: '特权码' ,width: 250 ,templte:(scope) =>{
          let {privileged_code, privileged_code_leave} = scope.row;
          return `上：${privileged_code || ''}</br>放：${privileged_code_leave || ''}`
        } },
      {prop: 'privileged_code_end_time',label: '特权码截止时间' ,width: 220  ,templte:(scope) =>{
          let {privileged_code_end_time, privileged_code_end_time_leave} = scope.row;
          return `上：${privileged_code_end_time || ''}</br>放：${privileged_code_end_time_leave || ''}`
        }  },

      // {prop: 'ticket_typall_name_leave',label: '回程票种名称' },
      // {prop: 'down_stop_id',label: '回程站点编号'  },
      // {prop: 'down_stop_name',label: '回程站点名称' },
      // {prop: 'identification_no_leave',label: '回程证件号码'},
      // {prop: 'identification_type_id_leave',label: '回程证件类型编号'},
      // {prop: 'identification_type_name_leave',label: '回程证件类型名称' },
      // {prop: 'passengers_id_leave',label: '回程乘车人编号'},
      // {prop: 'passengers_name_leave',label: '回程乘车人名称'},
      // {prop: 'customer_id_leave',label: '回程客户编号'},
      // {prop: 'customer_name_leave',label: '回程客户名称'},
      // {prop: 'out_trade_no_leave',label: '回程订单号' },
      // {prop: 'effective_time_start_leave',label: '车票有效时间起' },
      // {prop: 'effective_time_end_leave',label: '车票有效时间止' },
      // {prop: 'privileged_code_leave',label: '回程特权码' },
      // {prop: 'privileged_code_end_time_leave',label: '回程特权码截止时间' },
    ],
    confirmCallback: () => publicAllData(defDialogData.shuttle_seat_id),
    deleteCallback: () => publicAllData(defDialogData.shuttle_seat_id)
  };
  let {option,tableLoading,tableData,query,page,dialogRef,dialogShow,dialogData,dialogOption,defDialogData,isAppend,isDelete,isEdit,
    dialogConfirm,getDataList} = usePageList(opts);
  let shuttleId = '';
  watch(() => props.shuttleData, (newVal) => {
    if (newVal){
      let {shuttle_id,shuttle_name,shuttle_seat_id,shuttle_seat_name} = newVal;
      query.shuttle_seat_id = shuttle_seat_id || shuttle_id;
      shuttleId = shuttle_id;
      defDialogData.shuttle_seat_id = shuttle_seat_id || shuttle_id;
      defDialogData.shuttle_seat_name = shuttle_seat_name ||shuttle_name;
      getDataList();
    }
  },{immediate: true});
  let soleStatus = '',reserveStatus = '';

  option.hRBtns = [
    {title: '座位表改名',id: 'rename',type: 'primary',event: () => handleShow('rename')},
    {title: '生成',id: 'build',type: 'primary',event: () => handleShow('build')},
    // {title: '状态批改',id: 'statusUpdate',type: 'primary',event: () => handleShow('statusUpdate')},
    // {title: '票种批改',id: 'ticketUpdate',type: 'primary',event: () => handleShow('ticketUpdate')},
    {title: '删除',id: 'build',type: 'primary',event: () => handleShow('del')},
    {title: '清空月票',id: 'build',type: 'primary',event: () => clearAll('month')},
    {title: '清空',id: 'build',type: 'primary',event: () => clearAll('all')},
    // {title: '清空',id: 'build',type: 'primary',event: () => handleShow('clearSeat')},
  ];
  // option.colBtns.pop();
  option.colBtns = [];
  option.colBtns.push(
    {
      title: '留位',
      id: '',
      type: 'warning',
      //班车座位可售状态
      // filterMethod: (scope) => scope.row.seat_status_id == soleStatus.seat_status_id ||  scope.row.seat_status_id == soleStatus.seat_status_id,
      filterMethod: (scope) => scope.row.seat_status_id == 1 ||  scope.row.seat_status_id_leave == 1,
      event: (scope) => handleShow('reserveSeat',scope)
    },
    {
      title: '取消留位',
      id: '',
      type: 'danger',
      //班车座位留位状态
      filterMethod: (scope) => scope.row.seat_status_id == 3 ||  scope.row.seat_status_id_leave == 3,
      event: (scope) => handleShow('cancelReserveSeat',scope)
    },
    {
      title: '生成链接',
      id: '',
      type: 'primary',
      //班车座位留位状态
      filterMethod: (scope) => scope.row.seat_status_id == 3 ||  scope.row.seat_status_id_leave == 3,
      event: buildQrcode
    },
  )
  dialogOption.fieldList = [
    {field_id: 'shuttle_seat_id',label: '班车座位编号',type: 'text',col: 2 ,required: true,disabled: true },
    {field_id: 'shuttle_seat_name',label: '班车座位名称',type: 'text',col: 2 ,required: true,disabled: true},
    {field_id: 'seat_no',label: '座位号',type: 'number',col: 2 ,required: true,disabled: true },
    {col: 2 },

    {...refOpt.ticket_typall_id,col:2},
    {...refOpt.ticket_typall_name,col:2},
  ]

  prepare();

  let dialogs = {
    rename: {
      title: '座位表改名',
      fieldList: [
        {field_id: 'shuttle_seat_id',disabled: true, label: '班车座位号', type: 'text', col: 3, required: true},
        {field_id: 'new_shuttle_seat_name', label: '班车座位名', type: 'text', col: 3, required: true},
      ]
    },
    build: {
      title: '生成',
      fieldList: [
        {field_id: 'startNum', label: '起始座位号', type: 'text', col: 3,formatter: (value) => {
            let newVal = `${value}`.replace(new RegExp(/^[0]/g ), '');
            newVal = `${newVal}`.replace(new RegExp(/[^\d]/g ), '');
            return newVal;}},
        {field_id: 'num', label: '生成座位数', type: 'number', col: 3, required: true},
      ],
      show: false,
      data: {},
    },
    del: {
      title: '删除',
      fieldList: [
        {field_id: 'num', label: '删除座位数', type: 'number', col: 3, required: true},
      ],
      show: false,
      data: {},
    },
    statusUpdate: {
      title: '状态批改',
      fieldList: [
        {field_id: 'seat_no_start', label: '座位号起', type: 'number', col: 3,},
        {field_id: 'seat_no_end', label: '座位号止', type: 'number', col: 3, },
        {
          field_id: 'seat_status_name',
          label: '状态',
          type: 'reference',
          refUrl: getSeatStatus,
          refCols: [
            {label: '座位状态编号',prop: 'seat_status_id'},
            {label: '座位状态名称',prop: 'seat_status_name'},],entityKey: 'seat_status_name', valueKey: ['seat_status_id','seat_status_name'],
          col: 3,
        },
      ],
      show: false,
      data: {},
    },
    ticketUpdate: {
      title: '票种批改',
      fieldList: [
        {field_id: 'seat_no_start', label: '座位号起', type: 'number', col: 3, },
        {field_id: 'seat_no_end', label: '座位号止', type: 'number', col: 3, },
        {
          field_id: 'ticket_typall_id',
          label: '票种',
          type: 'reference',
          refUrl: getTicketType,
          refCols:[
            {prop: 'ticket_typall_id', label: '车票类型编号',},
            {prop: 'ticket_typall_name', label: '车票类型名称',},
          ],entityKey: 'ticket_typall_name', valueKey: ['ticket_typall_id','ticket_typall_name'],
          col: 3,
        },
      ],
      show: false,
      data: {},
    },
    reserveSeat: {
      title: '留位',
      fieldList: [
        {field_id: 'privileged_code', label: '特权码', type: 'text', col: 3,disabled: true},
        {field_id: 'privileged_code_end_time', label: '特权码截止时间', type: 'datetime', col: 3},
        {field_id: 'type',type: 'checkbox',col: 3,options: [{name:'去程',id: 'go'},{name: '回程',id: 'leave'}],required: true,requiredMsg: '留位时段不能为空'}

      ],
      show: false,
      data: {}
    },
    cancelReserveSeat: {
      title: '取消留位',
      fieldList: [
        {field_id: 'type',type: 'checkbox',col: 3,options: [{name:'去程',id: 'go'},{name: '回程',id: 'leave'}],required: true,requiredMsg: '取消留位时段不能为空',defaultValue: ['go','leave']}

      ],
      show: false,
      data: {}
    },
    /*clearSeat: {
      title: '清空座位',
      fieldList: [
        {field_id: 'ticket_type',label: '清空票种',type: 'checkbox',col: 3,options: [],required: true}
      ]
    }*/
  }
  let mDialog = ref({}),
    mDialogShow = ref(false),
    mDialogRef = ref(null),

    //生成二维码参数字段
    fields = [
      {...refOpt.shuttle_school_name,label: '站点(讫地)',col: 3,required: true,refParam: {shuttle_id: shuttleId}},
      {field_id: 'packag_type_id',type: 'picklist',options: [],optionId: 'packag_type_id',optionName: 'packag_type_name', label: '套票类型',col: 3,required: true},
      {...refOpt.shuttle_stop_name,field_id: 'stop_name_go',label: props.shuttleData.shuttle_type === '定制'? '去程上车站点':'去程上车站点',valueKey: [{stop_id_go: 'stop_id',},{stop_name_go: 'stop_name'}],col: 3,required: true,refParam: {shuttle_id: shuttleId,shuttle_direction_id: 'bcfx001'}},
      {...refOpt.shuttle_stop_name,field_id: 'stop_name_leave',label: props.shuttleData.shuttle_type === '定制'? '回程下车站点': '回程下车站点',valueKey: [{stop_id_leave: 'stop_id',},{stop_name_leave: 'stop_name'}],col: 3,required: true,refParam: {shuttle_id: shuttleId,shuttle_direction_id: 'bcfx002'}}
    ],
    linkField = ref([]),
    linkParam = ref({}),
    //留位生成链接
    qrcodeLink = ref(''),
    showQrcode = ref(false),    //二维码弹窗
    scopeRow = {},   //生成链接数据行
    formRef = ref(null),
    isBuilded = ref(false)

  //显示对应弹窗
  async function handleShow(id,scope) {
    if ((id === 'build' && !isAppend.value) || (id === 'del' && !isDelete.value) || ((id === 'reserveSeat' || id === 'cancelReserveSeat') && !isEdit.value )){
      ElMessage({
        type: 'warning',
        message: `抱歉，您没有${dialogs[id].title}权限`
      })
      return
    }
    //留位
    if (id === 'reserveSeat') {
      let {shuttle_seat_id, seat_no, seat_status_id,seat_status_id_leave} = scope.row,
        opts =[];
      //填充默认信息
      let def = {
        privileged_code: uuid(),
        shuttle_seat_id: shuttle_seat_id,
        seat_no: seat_no,
        type: []
      };
      //根据座位状态显示可勾选项
      if (seat_status_id == 1) {
        opts.push({name:'去程',id: 'go'});
        def.type.push('go')
      }
      if (seat_status_id_leave == 1) {
        opts.push({name: '回程',id: 'leave'});
        def.type.push('leave')
      }
      dialogs[id].data = def;
      dialogs[id].fieldList[2].options = opts;

    }
    //取消留位
    if (id === 'cancelReserveSeat') {
      let {shuttle_seat_id, seat_no, seat_status_id,seat_status_id_leave} = scope.row,
        opts =[];
      //填充默认信息
      let def = {
        shuttle_seat_id: shuttle_seat_id,
        seat_no: seat_no,
        type: []
      }
      //根据座位状态显示可勾选项
      if (seat_status_id == 3) {
        opts.push({name:'去程',id: 'go'});
        def.type.push('go')
      }
      if (seat_status_id_leave == 3) {
        opts.push({name: '回程',id: 'leave'});
        def.type.push('leave')
      }
      dialogs[id].data = def;
      dialogs[id].fieldList[0].options = opts;

    }

    // 生成
    if (id === 'build'){
      dialogs[id].fieldList[0].disabled = !!page.total;
      let startNum = 1;
      //有数据时，获取最后一条数据填充座位号
      page.total && await getShuttleSeat({shuttle_seat_id: defDialogData.shuttle_seat_id,'page.no': page.total,'page.size': 1}).then(res => {
        if (res.errcode != 0) return;
        let data = res.row[0];
        startNum = Number(data.seat_no) + 1;
      });
      dialogs[id].data = {startNum}
    }

    // 改名
    if (id === 'rename'){
      let {shuttle_seat_id,shuttle_seat_name} = props.shuttleData;
      let def = {
        shuttle_seat_id: shuttle_seat_id,
        new_shuttle_seat_name: shuttle_seat_name,
      };
      dialogs[id].data = def;
    }
    mDialog.value = dialogs[id];
    mDialogShow.value = true;
  }
  function handleConfirm(obj) {
    let {data,option} = obj;
    new Promise(resolve => {
      if (option.title === '生成') buildSeat(data.num,data.startNum || 1).then(() => resolve());
      else if (option.title === '删除') delSeat(data.num).then(() => resolve());
      else if (option.title === '留位') reserveSeat(data).then(() => resolve());
      else if (option.title === '取消留位') cancelReserveSeat(data).then(() => resolve());
      else if (option.title === '座位表改名') renameShuttleSeat(data)
      else updateSeat(data).then(() => resolve());
    }).then(() => {
      mDialogRef.value.close();
      getDataList();
      publicAllData(defDialogData.shuttle_seat_id);
    })
  }
  //生成座位
  function buildSeat(num,startNum) {
    tableLoading.value = true;
    return new Promise(resolve => {
      let datas = tableData.value,
        maxNo = page.total,
        list = [];
      for (let i = 0; i < num;i++){
        list.push({
          ...defDialogData,
          seat_status_id: soleStatus && soleStatus.seat_status_id,
          seat_status_name: soleStatus && soleStatus.seat_status_name,
          seat_status_id_leave: soleStatus && soleStatus.seat_status_id,
          seat_status_name_leave: soleStatus && soleStatus.seat_status_name,
          seat_no: Number(startNum) + i
        });
      }
      addShuttleSeat(list).then(async res => {
        if (res.errcode !== 0)return;
        await updateShuttleSeat();
        resolve()
      })
    })
  }
  //删除座位
  function delSeat(num) {
    tableLoading.value = true;
    return new Promise(async resolve => {
      let datas = tableData.value,
        maxNo = 0,
        pms = [];
      if (!page.total) {
        ElMessage({type: 'warning', message: '没有座位可删除'})
        tableLoading.value = false;
        return
      }
      //获取最后一条数据删除
      await getShuttleSeat({shuttle_seat_id: defDialogData.shuttle_seat_id,'page.no': page.total,'page.size': 1}).then(res => {
        if (res.errcode != 0) return;
        let data = res.row[0];
        maxNo = data ? data.seat_no : 0;
      });
      if (!maxNo){
        ElMessage({type: 'warning', message: '没有座位可删除'})
        tableLoading.value = false;
        return
      }
      for (let i = 0; i < num;i++){
        let param = {
            shuttle_seat_id: query.shuttle_seat_id,
            seat_no: maxNo--
          };
        // if (!data)break;
          pms.push(delShuttleSeat(param))
        if (maxNo === 0) break
      }
      Promise.all(pms).then(res => {
        tableLoading.value = false;
        resolve();
      })
    })
  }
  //更新座位
  function updateSeat(data,type) {
    tableLoading.value = true;
    return new Promise(resolve => {
      let datas = tableData.value,
        {seat_no_start,seat_no_end} = data,
        pms = [];
      delete data.seat_no_start;
      delete data.seat_no_end;

      datas.forEach(item => {
        if (seat_no_start <= item.seat_no <= seat_no_end) {
          let param = {
              shuttle_seat_id: item.shuttle_seat_id,
              seat_no: item.seat_no,
            ...data
            };

          pms.push(editShuttleSeatList(param))
        }
      })
      Promise.all(pms).then(res => {
        tableLoading.value = false;
        if (res.every(item => item.errcode === 0)) resolve();
      })
    })
  }
  //删除所有座位
  function clearAll(id){
    if (!isDelete.value){
      ElMessage({
        type: 'warning',
        message: '抱歉，您没有权限删除该模块数据'
      })
      return
    }
    let title = '清空座位表' ,
      msg =  '确定删除该班次所有座位？' ,
      api =  delShuttleSeatBySid;
    if (id === 'month'){
      title = '清空月票';
      msg = '确定清空该班次所有月票座位？';
      api = clearMonthTicket;
    }
    ElMessageBox.confirm(msg, title, {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm'){
          api(query.shuttle_seat_id).then(res => {
            if (res.errcode !== 0)return;
            ElMessage({
              type: 'success',
              message: `清空成功`,
            });
            getDataList();
            publicAllData(defDialogData.shuttle_seat_id);
          })
        }
      },
    })
  }
  //留位
  function reserveSeat(data){
    tableLoading.value = true;
    return new Promise(resolve => {
      if (data.type.includes('leave')){
        data.privileged_code_leave = data.privileged_code
        data.privileged_code_end_time_leave = data.privileged_code_end_time
        data.seat_status_id_leave = reserveStatus && reserveStatus.seat_status_id;
        data.seat_status_name_leave = reserveStatus && reserveStatus.seat_status_name;
      }
      if (!data.type.includes('go')){
        delete data.privileged_code
        delete data.privileged_code_end_time
      }else {
        data.seat_status_id = reserveStatus && reserveStatus.seat_status_id;
        data.seat_status_name = reserveStatus && reserveStatus.seat_status_name;
      }
      delete data.type;

      editShuttleSeat(data).then(res => {
        if (res.errcode !== 0)return;
        resolve();
      })
    })
  }
  //取消留位
  function cancelReserveSeat(data){
    tableLoading.value = true;
    return new Promise(resolve => {
      if (data.type.includes('go')){
        data.privileged_code = null;
        data.privileged_code_end_time = null;
        data.seat_status_id = soleStatus && soleStatus.seat_status_id;
        data.seat_status_name = soleStatus && soleStatus.seat_status_name;

      }
      if (data.type.includes('leave')){
        data.privileged_code_leave = null;
        data.privileged_code_end_time_leave = null;
        data.seat_status_id_leave = soleStatus && soleStatus.seat_status_id;
        data.seat_status_name_leave = soleStatus && soleStatus.seat_status_name;
      }
      delete data.type;

      editShuttleSeat(data).then(res => {
        if (res.errcode !== 0)return;
        resolve();
      })
    })

  }

  //更新主表座位编号、座位名称
  function updateShuttleSeat(){
    return new Promise(resolve => {

      let {shuttle_seat_id,shuttle_id,shuttle_name} = props.shuttleData;
      if (shuttle_seat_id) {
        resolve()
        return;
      }
      editShuttle({shuttle_id,shuttle_seat_id: shuttle_id,shuttle_seat_name: shuttle_name}).then(res => {
        resolve()
        if (res.errcode !== 0)return;
        refresh(shuttle_id);
      })
    })
  }

  function handleChange(obj) {
    qrcodeLink.value = obj;
    let {field} = obj,
      {field_id} = field,
      {seat_status_id,seat_status_id_leave,privileged_code,privileged_code_leave} = scopeRow,
      {packag_type_id,school_id} = linkParam.value;

    //选择站点
    if (field_id === 'school_name'){
      getPackageTypeBySchool({school_id,shuttle_type: props.shuttleData.shuttle_type}).then(res => {
        if (res.errcode !== 0)return;
        let row = res.row,
          arr = [];
        arr = row.filter(item => {
          //去程、回程座位状态为留位 且 去程回程特权码相同--只能选往返套票
          if (seat_status_id == 3 && seat_status_id_leave == 3 && privileged_code === privileged_code_leave ) return item.packag_type_id === 'tplx003'
          else {
            if (seat_status_id == 3 && seat_status_id_leave == 3) return (item.packag_type_id === 'tplx001' || item.packag_type_id === 'tplx002')
            if (seat_status_id == 3) return item.packag_type_id === 'tplx001'
            if (seat_status_id_leave == 3) return item.packag_type_id === 'tplx002'
          }
        })
        linkField.value = [linkField.value[0],{...fields[1],options: arr}];
        linkParam.vlaue = {...linkParam.value,packag_type_id: '',packag_type_name: ''}
        console.log(linkParam.vlaue);
        // linkField.push({...fields[1],options: arr});
      })
    }

    //选择套票类型
    if (field_id === 'packag_type_id') {
      let arr = [];
      if (packag_type_id === 'tplx003') {
        arr.push( fields[2],fields[3])
      }
      if (packag_type_id === 'tplx001') {
        arr.push( fields[2])
      }
      if (packag_type_id === 'tplx002') {
        arr.push( fields[3])
      }
      linkField.value = [linkField.value[0],linkField.value[1],...arr];
    }
  }
  //生成链接
  function buildQrcode(scope){
    scopeRow = scope.row;
    showQrcode.value = true;
    linkField.value = [fields[0]]
    linkParam.value= {};   //清空值
    isBuilded.value = false;
  }

  function buildConfirm() {
    formRef.value.validate(valid =>{
      if (valid) {
        let domain = process.env.VUE_APP_DOMAIN,
          weDir = process.env.VUE_APP_WECHATDIR;
        if (process.env.NODE_ENV !== 'development'){
          domain = window.webConfig.webApiBaseDomain;
          weDir = window.webConfig.wechatSecondDir;
        }
        let url = domain + weDir + 'buyTicket', //正式微信端网址
          query = [],
          {privileged_code,privileged_code_leave} = scopeRow,
          {packag_type_id} = linkParam.value,
          obj = {...linkParam.value,privileged_code: (packag_type_id === 'tplx002' ? privileged_code_leave : privileged_code),shuttle_id:shuttleId},
          keys = Object.keys(obj);
        query = keys.map(item => {
          return item + '=' + obj[item]
        });
        url = url + '?' + query.join('&');
        qrcodeLink.value = (process.env.NODE_ENV === 'development' ? process.env.VUE_APP_WECHAT_PATH : window.webConfig.webApiWechatPath) + '/api/v1/LoginWeChat/Index2?url=' + encodeURIComponent(str2Base64(url))
        isBuilded.value = true;
        // qrcodeLink.value = url
      }
    })
  }
  //复制链接
  function copyQrcode(){
    copyText(qrcodeLink.value).then(() => {
      ElMessage('复制成功')
    })
  }
  //清空月票信息
  function clearMonthTicket_(){
    ElMessageBox.confirm('确定清空该班次所有月票座位？', '清空月票', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm'){

          delShuttleSeatBySid(query.shuttle_seat_id).then(res => {
            if (res.errcode !== 0)return;
            ElMessage({
              type: 'success',
              message: `清空成功`,
            });
            getDataList();
            publicAllData(defDialogData.shuttle_seat_id);
          })
        }
      },
    })
  }

  //生成图片
  function buildImage() {
    var svgNode = document.querySelector('.qrcode-wrap svg');
    const svgData = new XMLSerializer().serializeToString(svgNode)
    const svgDataBase64 = btoa(unescape(encodeURIComponent(svgData)))

    const svgDataUrl = `data:image/svg+xml;charset=utf-8;base64,${svgDataBase64}`

    const img = new Image();
    img.src = svgDataUrl;
    img.onload = function() {
      const width = svgNode.getAttribute('width');
      const height = svgNode.getAttribute('height');
      const canvas = document.createElement('canvas');
      canvas.setAttribute('width', 424);
      canvas.setAttribute('height', 455);
      // canvas.setAttribute('style','background-color:#ffffff;')

      const context = canvas.getContext('2d');
      //画白色画布
      context.fillStyle = '#ffffff';
      context.fillRect(0,0,canvas.width,canvas.height);
      //画二维码
      context.drawImage(img, 12, 12, width, height);
      //画文字
      let text = props.shuttleData.shuttle_name,
        textWidth = context.measureText(text).width,
        position = (424 - textWidth)/2;
      position = position < 0 ? 0 : position;
      context.font = '16px serif';
      context.fillStyle = '#606266';
      context.fillText(text,position,440);// 绘制文字，实心的

      var aLink = document.createElement('a');
      aLink.style.display = "none";
      aLink.href = canvas.toDataURL('image/png', 1.0);
      aLink.download = text + '二维码';
      document.body.appendChild(aLink);
      aLink.click();
      document.body.removeChild(aLink);
    }
  }

  //座位表改名
  function renameShuttleSeat(data) {
    return new Promise(resolve => {
      changeShuttleSeatName(data).then(res =>{
        if (res.errcode != 0 ) return;
        let shuttleData = {...props.shuttleData,shuttle_seat_name: data.new_shuttle_seat_name }
        emit('update:shuttleData',shuttleData)
        mDialogRef.value.close();
        resolve();
      })
    })
  }

  function prepare(){
    let arr = [{title: '座位表改名',id: 'rename',type: 'primary',event: () => handleShow('rename')},];
    isAppend.value && arr.push({title: '生成',id: 'build',type: 'primary',event: () => handleShow('build')});
    isDelete.value && arr.push({title: '删除',id: 'build',type: 'primary',event: () => handleShow('del')},
      {title: '清空月票',id: 'build',type: 'primary',event: () => clearAll('month')},
      {title: '清空',id: 'build',type: 'primary',event: () => clearAll('all')})
    option.hRBtns = arr;

    let shuttleSeat_privileged  = getAuthority('shuttleSeat_privileged'),
      shuttleSeat_link = getAuthority('shuttleSeat_link');
    let arr2 = []
    if (shuttleSeat_privileged && shuttleSeat_privileged.is_see){
        arr2.push({
            title: '留位',
            id: '',
            type: 'warning',
            //班车座位可售状态
            // filterMethod: (scope) => scope.row.seat_status_id == soleStatus.seat_status_id ||  scope.row.seat_status_id == soleStatus.seat_status_id,
            filterMethod: (scope) => scope.row.seat_status_id == 1 ||  scope.row.seat_status_id_leave == 1,
            event: (scope) => handleShow('reserveSeat',scope)
          },
          {
            title: '取消留位',
            id: '',
            type: 'danger',
            //班车座位留位状态
            filterMethod: (scope) => scope.row.seat_status_id == 3 ||  scope.row.seat_status_id_leave == 3,
            event: (scope) => handleShow('cancelReserveSeat',scope)
          },)
    }
    if (shuttleSeat_link && shuttleSeat_link.is_see){
      arr2.push({
        title: '生成链接',
        id: '',
        type: 'primary',
        //班车座位留位状态
        filterMethod: (scope) => scope.row.seat_status_id == 3 ||  scope.row.seat_status_id_leave == 3,
        event: buildQrcode
      })
    }
    option.colBtns = arr2;
  }

  onBeforeMount(async () => {
    await getSeatStatus().then(res =>{
      if (res.errcode !== 0)return;
      let data = res.row;
      data.forEach(item => {
        if (item.seat_status_name === '可售') soleStatus = item;
        if (item.seat_status_name === '留') reserveStatus = item;
      });
    })

    //获取车票类型
    /*getTicketType().then(res => {
      if (res.errcode !== 0) return;
      let data = res.row,
        opts = [];
      data.forEach(item => {
        opts.push({name: item.ticket_typall_name,id: item.ticket_typall_id})
      });
      dialogs.clearSeat.fieldList[0].options = opts

    })*/

  })
</script>

<style scoped lang="less">
    .wrap{
        height: 100%;
        ::v-deep{
            .layout-header{
                padding: 0;
            }
            .layout-main{
                padding: 4px 0 0;
            }
        }

        .qrcode-wrap{
            display: flex;
            flex-direction: column;
            align-items: center;
            .title{
                font-size: 16px;
                margin-bottom: 20px;
            }
            .content{
                border: 2px solid #333333;
                padding: 10px;
                width: fit-content;
                text-align: center;
            }
        }
    }

</style>

